package com.lin.reggie.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lin.reggie.common.R;
import com.lin.reggie.dto.DishDto;
import com.lin.reggie.dto.SetmealDto;
import com.lin.reggie.entity.Dish;
import com.lin.reggie.entity.DishFlavor;
import com.lin.reggie.entity.Page;
import com.lin.reggie.entity.Setmeal;
import com.lin.reggie.mapper.DishFlavorMapper;
import com.lin.reggie.mapper.DishMapper;
import com.lin.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.events.Event;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;


    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;



    /**
     * 添加菜品
     * @param dishDto
     * @return boolean
     * */
    @Transactional
    @Override
    public boolean save2(DishDto dishDto) {
        //1.完善菜品对象数据
        //修改时间、添加时间、sort默认0，是否禁售设置1起售
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setSort(0);
        dishDto.setStatus(0);
        //2.调用数据访问层添加菜品，要求获取到添加菜品主键id
        dishMapper.insert(dishDto);//插入后里面就有菜品id

        //3.遍历口味记录列表完善数据
        List<DishFlavor>dishFlavorList=dishDto.getFlavors().stream().map((dishFlavor -> {
            //dishFlavor 是获取集合中的每个元素对象
            //（设置菜品的主键、更新时间、创建时间、更新人、创建人）
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            return dishFlavor;
        })).collect(Collectors.toList());
        //4.调用数据访问层插入多条口味记录数据
        dishFlavorMapper.save2(dishFlavorList);
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return true;
    }

    /**
     * 分页查询（连表查）
     * @param page
     * @param pageSize
     * @param name
     * @return page
     * */

    public Page<DishDto>findByPage2(Integer page , Integer pageSize , String name){
        //注意：对哪一条sql语句生成分页sql语句，这三局必须紧挨着
        PageHelper.startPage(page,pageSize);
        List<DishDto>dishDtoList=dishMapper.findAll2(name);
        PageInfo<DishDto> pageInfo = new PageInfo<>(dishDtoList);
        Page<DishDto> pageObj = new Page<>();
        pageObj.setRecords(pageInfo.getList());
        pageObj.setTotal(pageInfo.getTotal());
        return pageObj;
    }

    @Override
    public DishDto findById(Long id) {
        //1.根据id查找菜品
        Dish dish = dishMapper.findById(id);
        //2.根据菜品的id查找对应的口味  利用口味的成员调出方法，传入菜品id
        List<DishFlavor> byDishId = dishFlavorMapper.findByDishId(id);
        //3.创建DishDto,菜品、口味信息封装到DishDto里面
        DishDto dishDto = new DishDto();
        //将菜品id（dish）拷贝到dishDto对像里面
        BeanUtils.copyProperties(dish,dishDto);
        //根据获取的口味存到dishDto对象里
        dishDto.setFlavors(byDishId);
        //返回dishDto
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1. 补全修改时间
        dishDto.setUpdateTime(LocalDateTime.now());
        //2 修改菜品
        dishMapper.updateDish(dishDto);
        //3. 删除该菜品的所有口味信息
        dishFlavorMapper.deleteDishFlavor(dishDto.getId());

        //4. 补全口味信息，然后重新插入
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> dishFlavorList = flavors.stream().map((flavor ->{
            //对每一个元素进行加工
            flavor.setDishId(dishDto.getId());
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(dishDto.getCreateUser());
            flavor.setUpdateUser(dishDto.getUpdateUser());
            return flavor;
        })).collect(Collectors.toList());
        //4. 批量保存口味信息
        dishFlavorMapper.save2(dishFlavorList);
        //清楚缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
    }


    @Override
    public List<DishDto> findByCategoryId(Long categoryId ,Integer status ) {
        //0.查询缓存类别的菜品列表，key="dish_"+category+"_"+status"
        String key = "dish_" + categoryId + "_" + status;
        //查询到的数据为null，调用数据库查询
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList==null) {
            //1.调用mapper根据类别id和状态查询菜品列表
            List<Dish> dishList = dishMapper.findByCategoryIdAndStatus(categoryId, status);

            dishDtoList = dishList.stream().map((dish -> {
                //实例DishDto对象封装数据
                DishDto dishDto = new DishDto();

                BeanUtils.copyProperties(dish, dishDto);

                List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dishDto.getId());
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            })).collect(Collectors.toList());
            //将数据库查到的数据写入缓存
            redisTemplate.opsForValue().set(key,dishDtoList,300, TimeUnit.SECONDS);
        }
        return dishDtoList;
    }

    @Override
    public List<Setmeal> findAllSetmeal(Long categoryId, Integer status) {



        return null;
    }

}
